<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\QuestionModel;
use app\model\admin\TrainTypeModel;
use app\model\course\course\CourseLinkWare;
use app\model\course\ware\Courseware as CoursewareModel;
use app\model\teacher\Teacher as TeacherModel;
use think\Request;

class Courseware extends AuthController
{
    public function list(Request $request)
    {
        $page= input('page', 1);
        $limit = input('size', 10);
        $title = input('title', '');
        $ids = input('ids', '');
        $exclude_ids = input('exclude_ids', '');
        $company_id = input('company_id', '');
        $type_id = input('type_id', '');

        $data = CoursewareModel::order('id', 'desc')
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->when($company_id || $company_id === 0, function ($query) use ($company_id) {
                $query->where('company_id', $company_id);
            })
            ->when($ids, function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids, function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when(!empty($title), function ($query) use ($title) {
                $query->where('title', 'like', '%' . $title . '%');
            })
            ->with('teacher', 'company')
            ->where('status', 1)
            ->paginate($limit)
            ->each(function ($item) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->company_name = $item['company']['company_name'] ?? '平台';
                    $item->type_name = implode(',', $types);
                }
            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total()
        ]);
    }

    public function info(Request $request)
    {
        $teachers = TeacherModel::select();
        $id = input('id', '');
        if ($id) {
            $data = CoursewareModel::getOne($id);
            try {
                $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
                $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
            } catch (\Exception $e) {
                $data['type_ids'] = [];
            }
        } else {
            $data = null;
        }
        $types = DataType::getTrainType();
        if ($data && isset($data['teacher_id']) && $data['teacher_id'] == 0) {
            $data['teacher_id'] = '';
        }

        return app('json')->success([
            'teachers' => $teachers,
            'data' => $data,
            'types' => $types,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'type_ids', 'title', 'duration', 'hour', 'teacher_id', 'video_url', 'img_url',
            'topic_ids',
        ]);
        $id = input('id', '');
        $data['type_ids'] = ','.implode(',', $data['type_ids']).',';
        $data['resource_type'] = 2;
        if (!$id) {
            $res = CoursewareModel::create($data);
            $id = $res->id;
        } else {
            $res = CoursewareModel::update($data, ['id' => $id]);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $data = CoursewareModel::getOne($id);
        if (!$id || !$data) {
            return app('json')->fail('要操作的数据不存在');
        }
        // 查询是否有课程使用了该课件
        $exists = CourseLinkWare::where('courseware_id', $id)
            ->where('status', 1)
            ->count();
        if ($exists) {
            return app('json')->fail('当前课件已使用，不可删除');
        }
        CoursewareModel::dataDelete($id);
        return app('json')->success();
    }

    public function questionList(Request $request)
    {
        $where = [];
        $where[] = ['status', '=', 1];
        if ($title = $request->param('title', '')) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        if ($type = $request->param('type', '')) {
            $where[] = ['type', '=', $type];
        }
        $type_id = input('type_id', '');
        $data = QuestionModel::where($where)
            ->where('resource_type', 2)
            ->with('company')
            ->when($ids = input('ids', []), function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids = input('exclude_ids', []), function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->order('id desc')
            ->select()
            ->each(function ($item) {
                $options = '';
                $options2 = [];
                if ($item['a']) {
                    $options .= 'A.' . $item['a'];
                    $options2[] = 'A.' . $item['a'];
                }
                if ($item['b']) {
                    $options .= ' B.' . $item['b'];
                    $options2[] = 'B.' . $item['b'];
                }
                if ($item['c']) {
                    $options .= ' C.' . $item['c'];
                    $options2[] = 'C.' . $item['c'];
                }
                if ($item['d']) {
                    $options .= ' D.' . $item['d'];
                    $options2[] = 'D.' . $item['d'];
                }
                if ($item['e']) {
                    $options .= ' E.' . $item['e'];
                    $options2[] = 'E.' . $item['e'];
                }
                if ($item['f']) {
                    $options .= ' F.' . $item['f'];
                    $options2[] = 'F.' . $item['f'];
                }
                $item['options'] = $options;
                $item['options2'] = $options2;
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids']);
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item['type_name'] = implode(',', $types);
                } else {
                    $item['type_name'] = '';
                }

                if ($item['answer'] && is_array($item['answer'])) {
                    $item['answer'] = implode(',', $item['answer'] ?? []);
                }

                $item->company_name = $item['company']['company_name'] ?? '平台';
                return $item;
            });

        return app('json')->success([
            'list' => $data,
            'total' => count($data),
        ]);
    }

    public function questionAll(Request $request)
    {
        $limit = input('size', 10);
        $page = input('page', 1);

        $where = [];
        $where[] = ['status', '=', 1];
        $where[] = ['resource_type', '=', 2];
        if ($title = $request->param('title', '')) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        if ($type = $request->param('type', '')) {
            $where[] = ['type', '=', $type];
        }
        $type_id = input('type_id', '');
        $company_id = $request->param('company_id', '');
        if ($company_id || $company_id === 0) {
            $where[] = ['company_id', '=', $company_id];
        }

        $data = QuestionModel::where($where)
            ->with('company')
            ->when($ids = input('ids', []), function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids = input('exclude_ids', []), function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                $options = '';
                $options2 = [];
                if ($item['a']) {
                    $options .= 'A.' . $item['a'];
                    $options2[] = 'A.' . $item['a'];
                }
                if ($item['b']) {
                    $options .= ' B.' . $item['b'];
                    $options2[] = 'B.' . $item['b'];
                }
                if ($item['c']) {
                    $options .= ' C.' . $item['c'];
                    $options2[] = 'C.' . $item['c'];
                }
                if ($item['d']) {
                    $options .= ' D.' . $item['d'];
                    $options2[] = 'D.' . $item['d'];
                }
                if ($item['e']) {
                    $options .= ' E.' . $item['e'];
                    $options2[] = 'E.' . $item['e'];
                }
                if ($item['f']) {
                    $options .= ' F.' . $item['f'];
                    $options2[] = 'F.' . $item['f'];
                }
                $item['options'] = $options;
                $item['options2'] = $options2;
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids']);
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item['type_name'] = implode(',', $types);
                } else {
                    $item['type_name'] = '';
                }

                if ($item['answer'] && is_array($item['answer'])) {
                    $item['answer'] = implode(',', $item['answer'] ?? []);
                }

                $item->company_name = $item['company']['company_name'] ?? '平台';
                return $item;
            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }
}